package example.tallydemo;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.Date;

import example.tallydemo.MyActivity.AddBookActivity;
import example.tallydemo.MyActivity.SettingActivity;
import example.tallydemo.MyAdapter.MyFragmentAdapter;
import example.tallydemo.MyEntity.AccountBook;
import example.tallydemo.MyEntity.AccountManager;
import example.tallydemo.MyFragment.AnalyseFragment;
import example.tallydemo.MyFragment.HistoryFragment;
import example.tallydemo.MyFragment.MainFragment;
import example.tallydemo.MyFragment.MyBaseFragment;
import example.tallydemo.MyTools.MyTimeTool;
import example.tallydemo.MyView.MyViewPager;
import example.tallydemo.MyView.TzhRoundIcon;

public class MainActivity extends AppCompatActivity
{

    DrawerLayout drawerLayout;

    // 每一页就是一个Fragment
    MyBaseFragment[] pages = new MyBaseFragment[3];

    //适配器支持
    MyFragmentAdapter adapter;

    //accountManager 支持
    AccountManager accountManager;

    //工具类支持
    MyTimeTool myTimeTool;

    final int REQ_ADD_BOOK = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myTimeTool = new MyTimeTool();
        accountManager = new AccountManager(this);
        try
        {
            accountManager.load();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }


        drawerLayout = findViewById(R.id.layout_drawer);
        drawerLayout.setScrimColor(0xAACCCCCC);


        TzhRoundIcon roundIcon = findViewById(R.id.id_round_icon);
        roundIcon.setIcon( getDrawable(R.drawable.im_head2));



        initFragment();
    }

    private void initFragment()
    {
        pages[0] = new MainFragment();
        pages[0].setFragment(accountManager);
        pages[1] = new HistoryFragment();
        pages[1].setFragment(accountManager);
        pages[2] = new AnalyseFragment();
        pages[2].setFragment(accountManager);

        // 给ViewPager设置Adapter
        FragmentPagerAdapter pagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
        final MyViewPager viewPager = findViewById(R.id.id_viewpager);
        viewPager.setAdapter(pagerAdapter);

        MyFragmentAdapter.Item[] labels = new MyFragmentAdapter.Item[3];

        labels[0] = new MyFragmentAdapter.Item("首页","Main");
        labels[0].iconNormal = getDrawable(R.drawable.ic_meau_home_normal);
        labels[0].iconActive = getDrawable(R.drawable.ic_meau_home_active);

        labels[1] = new MyFragmentAdapter.Item("历史查看","History");
        labels[1].iconNormal = getDrawable(R.drawable.ic_meau_history_normal);
        labels[1].iconActive = getDrawable(R.drawable.ic_meau_history_active);

        labels[2] = new MyFragmentAdapter.Item("分析统计","Analyse");
        labels[2].iconNormal = getDrawable(R.drawable.ic_meau_analyse_normal);
        labels[2].iconActive = getDrawable(R.drawable.ic_meau_analyse_active);

        adapter = new MyFragmentAdapter(this);
        adapter.addItems(labels);

        ListView listView = findViewById(R.id.id_drawer_menu);
        listView.setAdapter(adapter);


        //设置默认第一个选项
        ((TextView)findViewById(R.id.id_titlebar_title))
                .setText((adapter.getRalItem(0)).getLabel());
        adapter.setActive(0,true);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                // 让ViewPager切换到对应的页
                viewPager.setCurrentItem(position,false);

                //设置 每个Fragment的标题栏属性
                String title;
                title = (adapter.getRalItem(position)).getLabel();
                Boolean flag;

                if (!(adapter.getRalItem(position)).getValue().equals("Main"))
                {
                    findViewById(R.id.id_titlebar_add).setVisibility(View.GONE);
                }
                else
                {
                    findViewById(R.id.id_titlebar_add).setVisibility(View.VISIBLE);
                }
                ((TextView)findViewById(R.id.id_titlebar_title)).setText(title);

                // 让GridView对应的标签高亮显示
                adapter.setActive(position, true);
                drawerLayout.closeDrawer(Gravity.START, true);
            }
        });
    }

    public void doStart(View view)
    {
        drawerLayout.openDrawer(Gravity.START, true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        accountManager = HandleData(requestCode,resultCode,data);
        // 分发给子Fragment处理
        for(MyBaseFragment f: pages)
        {
            String str = f.getClass().getName();
            String classname = str.substring(str.lastIndexOf(".")+1);

            if (classname.equals("MainFragment"))
            {
                f.setFragment(accountManager);
            }
            f.onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public AccountManager HandleData(int requestCode, int resultCode, Intent data)
    {
        if(requestCode == REQ_ADD_BOOK)
        {
            if(resultCode == RESULT_OK)
            {

                if (data.getStringExtra("date") == null)
                {
                    Toast.makeText(this, "时间为空", Toast.LENGTH_SHORT).show();
                }
                else if (data.getStringExtra("money").equals(""))
                {
                    Toast.makeText(this, "金额为空", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Boolean type = data.getBooleanExtra("type",true); //账本类型
                    String origin = data.getStringExtra("origin"); //账本来源
                    String classify = data.getStringExtra("classify"); //账本分类
                    Date date = myTimeTool.StringToDate(data.getStringExtra("date")); //账本日期
                    Double money = Double.valueOf(data.getStringExtra("money")); //账本金额
                    String introduction = data.getStringExtra("introduction"); //账本简介
                    myTimeTool.setDate(data.getStringExtra("date"));

                    AccountBook accountBook =
                            new AccountBook(null,type,origin,classify,date
                                    ,myTimeTool.getYear(),myTimeTool.getMonth(),myTimeTool.getDay()
                                    ,money,introduction);
                    accountManager.insert(accountBook);
                }
            }
        }
        return accountManager;
    }

    // ViewPager支持
    private class MyViewPagerAdapter extends FragmentPagerAdapter
    {
        public MyViewPagerAdapter(FragmentManager fm)
        {
            super(fm);
        }

        // 一共有几页
        @Override
        public int getCount()
        {
            return pages.length;
        }

        // 每一页的对象
        @Override
        public Fragment getItem(int position)
        {
            return pages[position];
        }
    }

    public void addItem(View view)
    {
        Intent intent = new Intent(this, AddBookActivity.class);
        startActivityForResult(intent,REQ_ADD_BOOK);
    }

    public void onSetting(View view)
    {
        Intent intent = new Intent(this, SettingActivity.class);
        startActivity(intent);
    }

}
